package top.laoliu.controller;

import com.sun.xml.internal.ws.resources.HttpserverMessages;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import top.laoliu.pojo.PositionResume;
import top.laoliu.pojo.PositionVo;
import top.laoliu.pojo.ResumeVo;
import top.laoliu.pojo.User;
import top.laoliu.service.DeliveryService;
import top.laoliu.service.PositionService;
import top.laoliu.service.ResumeService;
import top.laoliu.service.UserService;
import top.laoliu.util.SmsUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @Author: acer
 * @Date: 2020/10/9 15:38
 * @Description:
 */
@Controller
@RequestMapping({"/user", "/"})
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private PositionService positionService;

    @Autowired
    private DeliveryService deliveryService;

    @Autowired
    private ResumeService resumeService;

    @RequestMapping("/login")
    @ResponseBody
    public String login(User user,  HttpSession session) {
        String email = user.getEmail();
        String password = user.getPassword();
        System.out.println(user);
        if (userService.userLogin(email, password)) {
            User userByEmail = userService.getUserByEmail(email);
            System.out.println(userByEmail);
            session.setAttribute("user", userByEmail);
            session.setMaxInactiveInterval(60 * 60);
            System.out.println("登录成功");
            return "true";
        }
        System.out.println("登录失败");
        return "false";
    }

    @RequestMapping("/logout")
    public String logout(Model model, HttpSession session) {
        model.addAttribute("user", session.getAttribute("user"));
        session.removeAttribute("user");
        System.out.println("退出成功");
        return "forward:toLoginPage";
    }

    @RequestMapping({"/index", "/"})
    public String successToIndex(Model model) {
        List<PositionVo> positions = positionService.getLimitedPositionsByBrowsing(0, 4);
        List<String> positionNames = positionService.getLimitedPositionName();
        getClassificationSize(model);
        model.addAttribute("positionNames", positionNames);
        model.addAttribute("positions", positions);
        return "index";
    }

    private void getClassificationSize(Model model) {
        Integer artSum = positionService.getPositionByClassification("广告创意").size();
        model.addAttribute("artSum", artSum);
        Integer eduSum = positionService.getPositionByClassification("教育").size();
        model.addAttribute("eduSum", eduSum);
        Integer accountantSum = positionService.getPositionByClassification("会计").size();
        model.addAttribute("accountantSum", accountantSum);
        Integer hrSum = positionService.getPositionByClassification("人力资源").size();
        model.addAttribute("hrSum", hrSum);
        Integer internetSum = positionService.getPositionByClassification("工程师").size();
        model.addAttribute("internetSum", internetSum);
        Integer cateringSum = positionService.getPositionByClassification("餐厅").size();
        model.addAttribute("cateringSum", cateringSum);
        Integer architectureSum = positionService.getPositionByClassification("建设").size();
        model.addAttribute("architectureSum", architectureSum);
        Integer healthSum = positionService.getPositionByClassification("健康").size();
        model.addAttribute("healthSum", healthSum);
    }


    @RequestMapping("/getMessageCode")
    @ResponseBody
    public void getMessageCode(String phone, HttpSession session) {
        System.out.println("phone" + phone);
        try {
            if (session.getAttribute("messageCode") == null) {
                String messageCode = SmsUtils.getPhoneMessageCode(phone);
//                String messageCode = "831680";
                if (messageCode != null) {
                    session.setAttribute("messageCode", messageCode);
                    session.setMaxInactiveInterval(60);
                    System.out.println(messageCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/register")
    @ResponseBody
    public String register(User user, String messageCode, HttpSession session) {
        System.out.println("register" + user);
        System.out.println("register" + messageCode);
        System.out.println("register" + session.getAttribute("messageCode"));
        if (userService.isExistUser(user.getEmail(), user.getPhone())) {
            System.out.println("邮箱或手机号已被注册");
            return "邮箱或手机号已被注册";
        } else if (!messageCode.equalsIgnoreCase((String) session.getAttribute("messageCode"))) {
            System.out.println("验证吗21312312" + (String) session.getAttribute("messageCode"));
            System.out.println(messageCode.equalsIgnoreCase((String) session.getAttribute("messageCode")));
            System.out.println("验证码有误!");
            return "验证码有误!";
        } else if ("".equals(user.getUsername())) {
            return "请输入用户名";
        } else if ("".equals(user.getEmail())) {
            return "请输入邮箱";
        } else if ("".equals(user.getPhone())) {
            return "请输入电话号码";
        } else if ("".equals(user.getPassword())) {
            return "请输入密码";
        } else {
            userService.insertUser(user);
            System.out.println("注册成功");
            return "注册成功";
        }
    }

    @RequestMapping("/toRegisterPage")
    public String toRegisterPage() {
        return "register";
    }

    @RequestMapping("/toLoginPage")
    public String toLoginPage() {
        return "login";
    }

    @RequestMapping("/toChangePassword")
    public String toChangePassword() {
        return "userChangePassword";
    }

    @RequestMapping("/toUserProfile")
    public String toUserProfile() {
        return "userProfile";
    }

    @RequestMapping("/toUserJobManage")
    public String toUserJobManage(HttpSession session,Model model) {
        List<PositionVo> positions = new ArrayList<>();
        User user = (User) session.getAttribute("user");
        Integer user_id = user.getUser_id();
        List<PositionResume> deliveries = deliveryService.getDeliveriesByUserId(user_id);
        for (PositionResume positionResume:deliveries
             ) {
            Integer position_id = positionResume.getPosition_id();
            PositionVo positionById = positionService.getPositionById(position_id);
            //将投递状态放进去
            positionById.setStatus(positionResume.getStatus());
            //将投递日期放进去
            positionById.setDead_date(positionResume.getDelivery_date());
            positions.add(positionById);

        }
        System.out.println(positions);
        model.addAttribute("positions",positions);
        return "userJobManage";
    }

    @RequestMapping("/toUserResume")
    public String toUserResume(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        ResumeVo resume = resumeService.getResumeVoByUserId(user.getUser_id());
        System.out.println(resume);
        model.addAttribute("resume", resume);
        return "userResume";
    }

    @RequestMapping("/changePassword")
    @ResponseBody
    public String changePassword(String email, String oldPassword, String newPassword, String confirmPassword, HttpSession session) {
        System.out.println(email);
        System.out.println(oldPassword);
        System.out.println(newPassword);
        System.out.println(confirmPassword);
        boolean pwdIsTrue = userService.userLogin(email, oldPassword);
        if (!pwdIsTrue) {
            return "旧密码输入有误";
        } else {
            if (session.getAttribute("user") != null) {
                session.removeAttribute("user");
            }
            User userByEmail = userService.getUserByEmail(email);
            userByEmail.setPassword(newPassword);
            userService.updateUser(userByEmail);
            return "修改成功，请返回登录页面重新登录";
        }
    }


}
